package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.order.order.entity.dos.RankingAwards;
import cn.lili.modules.order.order.mapper.RankingAwardsMapper;
import cn.lili.modules.order.order.service.IRankingAwardsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 排名活动奖品配置表 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
public class RankingAwardsServiceImpl extends ServiceImpl<RankingAwardsMapper, RankingAwards> implements IRankingAwardsService {


    private void checkIsRepeatRankingNum(List<RankingAwards> rankingAwards) {
        //(新增,编辑排名活动)防止重复 名次条件 逻辑
        //冒泡排序
        this.bubbleSort(rankingAwards);
        for (int i = 0; i < rankingAwards.size(); i++) {
            if (i >= 1 && (rankingAwards.get(i).getRankingMin() <= rankingAwards.get(i - 1).getRankingMin() ||
                    rankingAwards.get(i).getRankingMin() <= rankingAwards.get(i - 1).getRankingMax())) {
                throw new ServiceException("名次条件重复");
            }
        }
    }

    public static void bubbleSort(List<RankingAwards> list) {
        int n = list.size();
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (list.get(j).getRankingMin() > list.get(j + 1).getRankingMin()) {
                    // 交换位置
                    RankingAwards temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
    }

    /**
     * 更新排名奖品信息
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBatchRankingAwards(List<RankingAwards> listParam, String configId) {
        LambdaQueryWrapper<RankingAwards> query = new LambdaQueryWrapper<>();
        query.in(RankingAwards::getActivityConfigId, configId);
        List<RankingAwards> rankingAwardsData = baseMapper.selectList(query);
        boolean flag = false;
        if (CollUtil.isNotEmpty(rankingAwardsData)) {
            //新增的奖品
            List<RankingAwards> newData = listParam.stream().filter(data -> StringUtils.isEmpty(data.getId())).collect(Collectors.toList());
            //拼接检查重复排名的list
            if (CollUtil.isNotEmpty(newData)) {
                List<RankingAwards> checkAwardsList = new ArrayList<>();
                checkAwardsList.addAll(newData);
                //取出旧的需要修改的奖品数据
                List<RankingAwards> newParamRwards = listParam.stream().filter(s -> StringUtils.isNotEmpty(s.getId())).collect(Collectors.toList());
                if(CollUtil.isNotEmpty(newParamRwards)){
                    checkAwardsList.addAll(newParamRwards);
                }
                //检查排名是否重复
                this.checkIsRepeatRankingNum(checkAwardsList);
            }else{
                //检查排名是否重复
                this.checkIsRepeatRankingNum(listParam);
            }

            //取出非新插入的数据
            List<String> paramIds = listParam.stream().filter(s -> StringUtils.isNotEmpty(s.getId())).map(RankingAwards::getId).collect(Collectors.toList());
            List<String> deleteDataIds = rankingAwardsData.stream().map(RankingAwards::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(paramIds) || (CollUtil.isNotEmpty(deleteDataIds) && (CollUtil.isEmpty(paramIds)))) {
                //取出需要删除的奖品ids
                deleteDataIds.removeAll(paramIds);
                if (CollUtil.isNotEmpty(deleteDataIds)) {
                    //删除的奖品
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.in("id", deleteDataIds);
                    updateWrapper.set("delete_flag", 1);
                    flag = this.update(updateWrapper);
                }
                //修改奖品
                flag = this.updateBatchById(listParam);
            }
            if (CollUtil.isNotEmpty(newData)) {
                newData.stream().forEach(e -> e.setActivityConfigId(configId));
                flag = this.saveBatch(newData);
            }
            if(!flag){
                throw new ServiceException("修改奖品失败");
            }
        }
        return 1;
    }


    /**
     * 根据活动id，获取所有活动奖品
     *
     * @param id 活动id
     * @return 所有活动奖品
     */
    @Override
    public List<RankingAwards> getAwardsByActivity(String id) {
        LambdaQueryWrapper<RankingAwards> rankingAwardsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        rankingAwardsLambdaQueryWrapper.eq(RankingAwards::getActivityConfigId, id);
        return super.list(rankingAwardsLambdaQueryWrapper);
    }
}
